//
//  UIScrollView+Adapter.m
//  IMPStudy
//
//  Created by 王会洲 on 16/12/12.
//  Copyright © 2016年 王会洲. All rights reserved.
//

#define ResponTag 30000


#import "UITableView+Adapter.h"
#import <objc/runtime.h>
#import "UIView+Addition.h"

static const void * dataSource = &dataSource;

@implementation UITableView (Adapter)
@dynamic emptyPlaceholderDelegate;

+ (void)load {
    [self swizzleMethod:@selector(reloadData) withMethod:@selector(__reloadData) error:nil];
}

/**
 + 替换两个方法IMP
 
 @param origSel_ reloadata
 @param altSel_ customFun
 @param error_ error
 @return bool
 */
+ (BOOL)swizzleMethod:(SEL)origSel_ withMethod:(SEL)altSel_ error:(NSError * *)error_ {
    Method origMethod = class_getInstanceMethod(self, origSel_);
    if (! origMethod) {
        return NO;
    }
    
    Method altMethod = class_getInstanceMethod(self, altSel_);
    if (! altMethod) {
        return NO;
    }
    
    class_addMethod(self,
                    origSel_,
                    class_getMethodImplementation(self, origSel_),
                    method_getTypeEncoding(origMethod));
    
    class_addMethod(self,
                    altSel_,
                    class_getMethodImplementation(self, altSel_),
                    method_getTypeEncoding(altMethod));
    
    method_exchangeImplementations(class_getInstanceMethod(self, origSel_), class_getInstanceMethod(self, altSel_));
    return YES;
}

- (id<EmptyPlaceholderDelegate>)emptyPlaceholderDelegate {
    return objc_getAssociatedObject(self, &dataSource);
}

-(void)setEmptyPlaceholderDelegate:(id<EmptyPlaceholderDelegate>)emptyPlaceholderDelegate {
    objc_setAssociatedObject(self, &dataSource,emptyPlaceholderDelegate,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (void)__reloadData {
    [self __reloadData];
    
    NSInteger items = 0;
    
    UITableView *tableView = (UITableView *)self;
    id <UITableViewDataSource> dataSource = tableView.dataSource;
    
    if (dataSource && [dataSource respondsToSelector:@selector(tableView:numberOfRowsInSection:)]) {
        items = [dataSource tableView:tableView numberOfRowsInSection:0];
    }
    
    if (self.emptyPlaceholderDelegate && [self.emptyPlaceholderDelegate respondsToSelector:@selector(responsEmptyPlaceholderView:)]) {
        if (0 == items) {
            [self removePlaceholderView];
            UIView * responView = [self.emptyPlaceholderDelegate responsEmptyPlaceholderView:self];
            responView.tag = ResponTag;
            self.tableFooterView = responView;
        } else {
            [self removePlaceholderView];
        }
    }
}

- (void)removePlaceholderView {
    UIView * customView = [self viewWithTag:ResponTag];
    if (customView) {
        [customView removeFromSuperview];
    }
}


@end
